package com.onstar.cn.map.route;

import android.content.Context;
import android.graphics.Color;
import android.text.Spanned;
import android.util.SparseArray;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.model.BitmapDescriptor;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.model.Polyline;
import com.amap.api.maps2d.model.PolylineOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.DriveStep;
import com.onstar.cn.map.common.Language;
import com.onstar.cn.map.util.ChString;
import com.onstar.cn.map.util.MapUtil;

import java.util.ArrayList;
import java.util.List;

public class RouteOverlay /* implements OnMarkerClickListener, InfoWindowAdapter */{

	private AMap mMap;
	private DrivePath mRoute;
	private LatLng startPoint;
	private LatLng endPoint;
	private SparseArray<Marker> markerMap;
	private List<Polyline> routePolylines;
	private int currentIndex = 0;
	private static int zoomLevel = 15;
	private BitmapDescriptor startIcon;
	private BitmapDescriptor endIcon;
	private BitmapDescriptor wayIcon;

	public RouteOverlay(Context context, AMap map) {
		mMap = map;
		// mMap.setOnMarkerClickListener(this);
		// mMap.setInfoWindowAdapter(this);
		markerMap = new SparseArray();
		routePolylines = new ArrayList<Polyline>();
	}

	public void setRoute(DriveRouteResult route) {
		this.mRoute = route.getPaths().get(0);
		startPoint = SearchPointConvert(route.getStartPos());
		endPoint = SearchPointConvert(route.getTargetPos());
	}

	public void setMarkerIcons(BitmapDescriptor startIcon, BitmapDescriptor endIcon, BitmapDescriptor wayIcon) {
		this.startIcon = startIcon;
		this.endIcon = endIcon;
		this.wayIcon = wayIcon;
	}

	/**
	 * 缁樺埗鑺傜偣鍜岀嚎璺?
	 */
	public void addMarkerLine() {
		Marker startMarker = mMap.addMarker((new MarkerOptions()).position(
				startPoint).icon(
				startIcon)
		/* .title("0") */);
		// startMarker.showInfoWindow();

		markerMap.put(0, startMarker);
		for (int i = 0; i < mRoute.getSteps().size(); i++) {
			DriveStep segment = mRoute.getSteps().get(i);
			if (i != 0) {
				BitmapDescriptor icon = null;

				icon = wayIcon;
				Marker tempMarker = mMap
						.addMarker((new MarkerOptions())
								.position(
										SearchPointConvert(segment
												.getPolyline().get(0))).icon(icon)
								.anchor(0.5f, 0.5f)/* .title("" + i) */);
				markerMap.put(i, tempMarker);

			}
			Polyline pline = mMap.addPolyline((new PolylineOptions())
					.addAll(convertArrList(segment.getPolyline()))
					.color(Color.argb(180, 54, 114, 227)).width(10.9F));
			routePolylines.add(pline);
		}
		Marker targerMarker = mMap.addMarker((new MarkerOptions()).position(
				endPoint).icon(endIcon)
		/* .title("" + (mRoute.getStepCount())) */);
		markerMap.put(mRoute.getSteps().size(), targerMarker);

	}

	/**
	 * 娓呴櫎缁樺埗
	 */
	public void removeFromMap() {
		if (this.routePolylines == null || this.markerMap == null) {
			return;
		}
		for (Polyline pline : routePolylines) {
			pline.remove();
		}
		markerMap.clear();
//		for (Marker marker : markerMap.values()) {
//			marker.remove();
//		}
	}

	public boolean showPrePopInfo() {
		if (currentIndex > 0) {
			currentIndex--;
			Marker merker = markerMap.get(currentIndex);
			mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
					merker.getPosition(), zoomLevel));
			merker.showInfoWindow();
		}
		return currentIndex != 0;
	}

	public boolean showNextPopInfo() {
		if (currentIndex < mRoute.getSteps().size()) {
			currentIndex++;
			Marker merker = markerMap.get(currentIndex);
			mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
					merker.getPosition(), zoomLevel));
			merker.showInfoWindow();
		}
		return currentIndex != mRoute.getSteps().size();
	}

	/**
	 * 鏍规嵁Segment index 鐢熸垚popInfo view
	 * 
	 * @param index
	 * @return
	 */
	public View getInfoView(Context cnt, int index) {
		if (index < 0 || index > mRoute.getSteps().size()) {
			return null;
		}

		LinearLayout ll_parents = new LinearLayout(cnt);
		ll_parents.setOrientation(LinearLayout.VERTICAL);
		ll_parents.setBackgroundResource(0);

		LinearLayout ll_child1 = new LinearLayout(cnt);
		ll_child1.setOrientation(LinearLayout.HORIZONTAL);
		ll_child1.setGravity(Gravity.AXIS_PULL_BEFORE);
		TextView titleVw = new TextView(cnt);
		String spannedInfos[] = getSpannedInfo(index).toString()
				.split("\\n", 2);
		titleVw.setTextColor(Color.BLACK);
		titleVw.setText(MapUtil.stringToSpan(spannedInfos[0]));
		titleVw.setPadding(3, 0, 0, 3);
		ll_child1.addView(titleVw, new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.MATCH_PARENT,
				LinearLayout.LayoutParams.WRAP_CONTENT));

		TextView backgroud = new TextView(cnt);
		backgroud.setBackgroundColor(Color.rgb(165, 166, 165));
		backgroud.setLayoutParams(new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.MATCH_PARENT, 1));

		LinearLayout ll_child3 = new LinearLayout(cnt);
		ll_child3.setOrientation(LinearLayout.VERTICAL);

		TextView titleVwdown = new TextView(cnt);
		if (spannedInfos.length == 2) {
			ll_child3.addView(backgroud, new LinearLayout.LayoutParams(
					LinearLayout.LayoutParams.MATCH_PARENT, 1));

			titleVwdown.setText(MapUtil.stringToSpan(spannedInfos[1]));
			titleVwdown.setTextColor(Color.rgb(82, 85, 82));
			ll_child3.addView(titleVwdown, new LinearLayout.LayoutParams(
					LinearLayout.LayoutParams.MATCH_PARENT,
					LinearLayout.LayoutParams.WRAP_CONTENT));
		}

		LinearLayout ll_child2 = new LinearLayout(cnt);
		ll_child2.setOrientation(LinearLayout.HORIZONTAL);
		ll_child2.setGravity(Gravity.CENTER_HORIZONTAL);

		ll_parents.addView(ll_child1, new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.MATCH_PARENT,
				LinearLayout.LayoutParams.WRAP_CONTENT));

		ll_parents.addView(ll_child3, new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.MATCH_PARENT, 1));

		ll_parents.addView(ll_child2, new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.MATCH_PARENT,
				LinearLayout.LayoutParams.WRAP_CONTENT));

		return ll_parents;
	}

	/**
	 * 鑾峰彇popInfo鎻忚堪
	 * 
	 * @param index
	 * @return
	 */
	public Spanned getSpannedInfo(int index) {
		if (index == mRoute.getSteps().size()) {
			StringBuffer buf = new StringBuffer();
			buf.append(ChString.Arrive);
			buf.append("Target");
			return MapUtil.stringToSpan(buf.toString());
		}

		return getCarInfo(index);

	}

	/**
	 * 鑾峰彇椹捐溅popInfo鎻忚堪
	 * 
	 * @param index
	 * @return
	 */
	public Spanned getCarInfo(int index) {
		String content = "";
		DriveStep seg = mRoute.getSteps().get(index);
		if (!MapUtil.IsEmptyOrNullString(seg.getRoad())
				&& !MapUtil.IsEmptyOrNullString(seg.getInstruction())) {
			content = seg.getAction() + " --> " + seg.getRoad();
		} else {
			content = seg.getAction() + seg.getRoad();
		}

		content = MapUtil.colorFont(content, MapUtil.HtmlGray);
		content += MapUtil.makeHtmlNewLine();
		content += String.format("%s%s", ChString.About,
				MapUtil.getFriendlyLength(seg.getDistance(),Language.ZH_CN));

		return MapUtil.stringToSpan(content);
	}

	/**
	 * 宸ュ叿鏂规硶锛? 灏嗕竴涓猻egment shaps 杞寲鎴恗ap鐨凩atLng list 鏂逛究娣诲姞鍒板湴鍥?
	 * 
	 * @param shapes
	 * @return
	 */
	private ArrayList<LatLng> convertArrList(List<LatLonPoint> shapes) {
		ArrayList<LatLng> lineShapes = new ArrayList<LatLng>();
		for (LatLonPoint point : shapes) {
			LatLng latLngTemp = SearchPointConvert(point);
			lineShapes.add(latLngTemp);
		}
		return lineShapes;
	}

	/**
	 * 宸ュ叿鏂规硶锛屽皢鎼滅储寰楀埌鐨凩atLonPoint杞垚latLng 鎵嶈兘娣诲姞鍒板湴鍥句笂
	 * 
	 * @param latLonPoint
	 * @return
	 */
	private LatLng SearchPointConvert(LatLonPoint latLonPoint) {
		return new LatLng(latLonPoint.getLatitude(), latLonPoint.getLongitude());
	}
}
